<?php


namespace app\finance\controller;


use app\base\BaseController;
use think\facade\Db;
use think\facade\View;

class OtherIncome extends BaseController
{
    protected $title='收支明细';
    protected $table='money_records';

    public function index()
    {
        $param=$this->request->param();
        if (request()->isAjax()) {
            $where[]=['mr.status','>',-1];
            $where[]=['mr.orderType','=',6];

            if (isset($this->param['mType'])&&$this->param['mType']){
                $where[]=['mr.mType','=',$this->param['mType']];
            }
            if (isset($this->param['name'])&&$this->param['name']){
                $where[]=['ad.name|mr.remark','like','%'.$this->param['name'].'%'];
            }
            if (isset($this->param['orderDate'])&&$this->param['orderDate']){
                $dates=explode('~',$this->param['orderDate']);
                $where[]=['mr.orderDate','between',$dates];
            }
            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
            $list = Db::name($this->table)
                ->alias('mr')
                ->leftJoin('admin ad','ad.id=mr.createId')
                ->where($where)
                ->field('mr.*,ad.name as userName')
                ->order('mr.id DESC')
                ->paginate($rows);
            $countIn=Db::name($this->table)
                ->alias('mr')
                ->leftJoin('admin ad','ad.id=mr.createId')
                ->where($where)
                ->where('mr.mType',1)
                ->sum('money');
            $countOut=Db::name($this->table)
                ->alias('mr')
                ->leftJoin('admin ad','ad.id=mr.createId')
                ->where($where)
                ->where('mr.mType',2)
                ->sum('money');
            return table_assign(0, '操作成功', $list,$httpCode = 200, $header = [], $options = [],$others=['countIn'=>$countIn,'countOut'=>$countOut]);
        } else {
            return view();
        }
    }

    public function add()
    {
        $param=$this->param;
        $id=$param['id']??0;
        if ($this->request->post()){
            $param['update_time'] = time();
            try {
                if ($id){
                    add_log('edit', $id, $this->param,$this->title);
                    Db::name($this->table)->save($param);
                }else{
                    unset($param['id']);
                    $param['createId']=$this->uid;
                    $param['orderType']=6;
                    $param['create_time'] = time();
                    $id=Db::name($this->table)->insertGetId($param);
                    add_log('add', $id, $this->param,$this->title);
                }

            }catch (\Exception $e){
                return to_assign(1,'操作失败：'.$e->getMessage());
            }
            return  to_assign();

        }else{

            View::assign('id',$id);
            return view('form');
        }
    }

}